<template>
  <div class="model-problem-stats">
    <el-card class="stats-card">
      <template #header>
        <div class="card-header">
          <span>型号问题统计</span>
          <el-icon><DataAnalysis /></el-icon>
        </div>
      </template>
      
      <div class="chart-container">
        <v-chart 
          class="chart" 
          :option="chartOption" 
          autoresize
        />
      </div>
      
      <div class="stats-summary" v-if="summaryData">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="summary-item">
              <div class="summary-label">总问题数</div>
              <div class="summary-value">{{ summaryData.totalProblems }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="summary-item">
              <div class="summary-label">Top型号</div>
              <div class="summary-value">{{ summaryData.topModel }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="summary-item">
              <div class="summary-label">警报状态</div>
              <div class="summary-value" :class="{ 'alert': hasAlert }">
                {{ hasAlert ? '⚠️ 需要关注' : '✅ 正常' }}
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import VChart from 'vue-echarts'
import { DataAnalysis } from '@element-plus/icons-vue'
import { getModelProblemStats } from '../api/anr'
import { useAnrStore } from '../stores/anr'
import { storeToRefs } from 'pinia'

// 使用全量版 ECharts（在 main.js 引入 'echarts'），无需按需 use 注册

const chartData = ref([])
const summaryData = ref(null)
const loading = ref(false)

const hasAlert = computed(() => {
  return chartData.value.some(item => item.isAlert)
})

const chartOption = computed(() => {
  if (!chartData.value.length) {
    return {
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'middle',
        textStyle: {
          color: '#999'
        }
      }
    }
  }

  const models = chartData.value.map(item => item.model)
  const counts = chartData.value.map(item => item.count)
  const percentages = chartData.value.map(item => item.percentage)
  const isAlerts = chartData.value.map(item => item.isAlert)

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const param = params[0]
        const dataIndex = param.dataIndex
        const item = chartData.value[dataIndex]
        return `
          <div style="padding: 10px;">
            <div><strong>${item.model}</strong></div>
            <div>问题数量: ${item.count}</div>
            <div>占比: ${item.percentage}%</div>
            <div style="color: ${item.isAlert ? '#ff4d4f' : '#52c41a'}">
              ${item.isAlert ? '⚠️ 需要关注' : '✅ 正常'}
            </div>
          </div>
        `
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: models,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '问题数量'
    },
    series: [
      {
        name: '问题数量',
        type: 'bar',
        data: counts.map((count, index) => ({
          value: count,
          itemStyle: {
            color: isAlerts[index] ? '#ff4d4f' : '#1890ff'
          }
        })),
        barWidth: '60%',
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        }
      }
    ]
  }
})

const anrStore = useAnrStore()
const { timeRange, customDateRange, selectedModels } = storeToRefs(anrStore)

const loadData = async () => {
  loading.value = true
  try {
    const response = await getModelProblemStats({
      timeRange: timeRange.value,
      customDateRange: customDateRange.value,
      models: selectedModels.value
    })
    if (response.status === 'success') {
      chartData.value = response.data
      summaryData.value = {
        totalProblems: response.totalProblems,
        topModel: response.topModel
      }
    } else {
      console.error('获取数据失败:', response.message)
    }
  } catch (error) {
    console.error('获取型号问题统计失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => { loadData() })
watch([timeRange, customDateRange, selectedModels], () => { loadData() })
</script>

<style scoped>
.model-problem-stats {
  margin-bottom: 20px;
}

.stats-card {
  height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.chart {
  height: 100%;
  width: 100%;
}

.stats-summary {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.summary-item {
  text-align: center;
}

.summary-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.summary-value.alert {
  color: #ff4d4f;
}
</style>

